package ut.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
public class Verify extends HttpServlet{
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		request.setCharacterEncoding("utf-8");
		// 取得並驗證使用者輸入資訊
		String source, id, code;
		if(request.getParameter("source") == null || request.getParameter("id") == null || request.getParameter("code") == null){
			return;
		}else{
			source = request.getParameter("source");
			id = request.getParameter("id");
			code = request.getParameter("code");
		}
		ut.data.User user = (ut.data.User)request.getSession().getAttribute("user");
		if(source.equals("email")){
			if(user != null && user.verify > 0){ // 已經驗證通過了，表達成功即可
				response.sendRedirect("/account/verify.jsp?result=success"); // 驗證成功
			}else if(ut.util.MD5.digestToHex(id + " at ultimate translation (!@$^#!^*&)").equals(code)){
				if(ut.data.User.verifiedEmail(Integer.parseInt(id))){
					// 若使用者已經登入此驗證的帳號，更新 Session 中的物件
					if(user != null && user.id == Integer.parseInt(id)){
						user.verify = 1;
						user.notify = true;
					}
					response.sendRedirect("/account/verify.jsp?result=success"); // 驗證成功
				}else{
					response.sendRedirect("/account/verify.jsp?result=again"); // 系統錯誤，請重試一次
				}
			}else{
				response.sendRedirect("/account/verify.jsp?result=fail"); // 驗證失敗
			}
		}else if(source.equals("phone")){
			if(user != null){
				if(user.verify == 2){ // 已經驗證通過了，表達成功即可
					response.setHeader("result", "true"); // 驗證成功
				}else if(ut.data.User.verifiedPhone(user, code)){
					response.setHeader("result", "true"); // 驗證成功
				}else{
					response.setHeader("result", "false"); // 系統錯誤，請重試一次
				}
			}else{
				response.setHeader("result", "false"); // 驗證失敗
			}
		}else{
			response.sendRedirect("/"); // 驗證參數不正確，直接導回首頁
		}
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		doGet(request, response);
	}	
}